import api, { commonApi, VERSION } from './api.js';
var reqestMethod = {
    GET: 'GET',
    POST: 'POST'
};
/**
 * @param url 请求路径
 * @param params 请求数据
 * @param metod  请求方式
 * @param head   请求头
 * @param beforerequest 请求前
 * @param endrequest   请求后
 * @param success  请求成功
 * @param fail   请求失败
 * @param isAuthorityToken   接口参数中是否有token
 */
function requestLoading(url, params, method, header, beforerequest, endrequest, success, fail, isAuthorityToken = false) {
    if (beforerequest) {
        beforerequest();
    }
    var token ={"clienttype":"weixx","clienttoken":"5F323D104358E614518AD233FF3305FEEED6F6A41A54319EDB7677A1A0D7FE7A23103082F16EDFB0E793DBC33CA27681681995F07D11555266BEC26CC5B1A812693835CDDBF775B51E6416111E05C4527BCCD97C4602B961F1AEF9B2519CBFB31B601E25575D280312B3A548E4309591574A84AD281356619B84DE009CF9F6C9","ordertoken":"","version":"1.3.12"}
    params['token'] =token ;
    params['org'] = '88621533'
    if (check.isNull(method)) {
        method = reqestMethod.GET;
    }
    if (header == null) {
        if (method == reqestMethod.POST) {
            header = {
                'Content-Type': 'application/x-www-form-urlencoded',
                Accept: 'application/json, text/javascript'
            };
        } else {
            header = {
                'Content-Type': 'application/json, text/javascript',
                Accept: 'application/json, text/javascript,'
            };
        }
    }
    uni.request({
        url: url,
        data: params,
        header: header,
        method: method,
        dataType: 'json',
        success: function (res) {
            if (res != null && (res.statusCode == 550 || res.statusCode == 400 || res.statusCode == 502 || res.statusCode == 404)) {
                fail(res);
            } else if (res.statusCode == 200) {
                success(res.data);
            }
        },
        fail: function (res) {
            fail(res);
        },
        complete: function (res) {
            if (endrequest) {
                endrequest();
            }
        }
    });
}
function getHours(nowhour) {
    var result = [];
    for (var i = nowhour; i < 24; i++) {
        var getresult = i;
        if (getresult < 10) {
            getresult = '0' + getresult;
        }
        result.push(getresult + '时');
    }
    return result;
}
function getWeek(param) {
    var result = '';
    switch (param) {
        case 1:
            result = '星期一';
            break;
        case 2:
            result = '星期二';
            break;
        case 3:
            result = '星期三';
            break;
        case 4:
            result = '星期四';
            break;
        case 5:
            result = '星期五';
            break;
        case 6:
            result = '星期六';
            break;
        case 0:
            result = '星期日';
            break;
    }
    return result;
}
//比较时间大小
function compareTime(startDate, endDate) {
    if (startDate.length > 0 && endDate.length > 0) {
        var startDateTemp = startDate.split('.');
        var endDateTemp = endDate.split('.');
        // var arrStartDate = startDateTemp[0].split("-");
        // var arrEndDate = endDateTemp[0].split("-");
        // var arrStartTime = startDateTemp[1].split(":");
        // var arrEndTime = endDateTemp[1].split(":");
        var allStartDate = new Date(startDateTemp[0], startDateTemp[1], startDateTemp[2]);
        var allEndDate = new Date(endDateTemp[0], endDateTemp[1], endDateTemp[2]);
        if (allStartDate.getTime() <= allEndDate.getTime()) {
            return true;
        } else {
            return false;
        }
    }
}
/*
 * 判断是否微信
 */
function isWeiXin() {
	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true;
	} else {
		return false;
	}
}
function getToday(){
  var myDate = new Date();
  var Year = myDate.getFullYear();
  var Month = myDate.getMonth() + 1;
  var Day = myDate.getDate();
  Month = addzero(Month);
  Day = addzero(Day);
  return Year + "-" + Month + "-" + Day
}
/*
 * 判断是否是微信小程序
 */
function isWeiXinMiniprogram() {
	var environment = window.__wxjs_environment;
	return (sessionStorage.fromto && sessionStorage.fromto == "weixx") || (environment && environment == "miniprogram")
}
/**
 * @param url 请求路径
 * @param params 请求数据
 * @param metod  请求方式
 * @param head   请求头
 * @param beforerequest 请求前
 * @param endrequest   请求后
 * @param success  请求成功
 * @param fail   请求失败
 * @param isAuthority   接口是否鉴权
 */
function requestAfterLogin(url, params, method, header, beforerequest, endrequest, success, fail, isAuthority) {
    // 全局变量
    var globalData = getApp().globalData;
    // 如果正在进行登陆，就将非登陆请求放在队列中等待登陆完毕后进行调用
    if (globalData.isLanding) {
        var catchRequest = {
            url,
            params,
            method,
            header,
            beforerequest,
            endrequest,
            success,
            fail,
            isAuthority
        };
        globalData.requestQueue.push(catchRequest);
        return;
    }
    requestLoading(url, params, method, header, beforerequest, endrequest, success, fail, isAuthority);
}
/**
 * 网络请求鉴权
 */

function getShowWeek(_year, _month, _day) {
    let app = getApp();
    //今天
    let today_year = app.globalData.Year;
    let today_month = app.globalData.Month;
    let today_day = app.globalData.Day;
    //明天
    let curDate = new Date();
    let tomorrowdate = new Date(curDate.getTime() + 86400 * 1000);
    let tomorrowY = tomorrowdate.getFullYear();
    let tomorrowM = addzero(tomorrowdate.getMonth() + 1);
    let tomorrowD = addzero(tomorrowdate.getDate());
    let _ymd = _year + '-' + _month + '-' + _day;
    let todaystr = today_year + '-' + today_month + '-' + today_day;
    let tomorrowstr = tomorrowY + '-' + tomorrowM + '-' + tomorrowD;
    if (_ymd == todaystr) {
        return '今天';
    } else if (_ymd == tomorrowstr) {
        return '明天';
    } else {
        let date = new Date(_ymd);
        return app.globalData.weekDay[date.getDay()];
    }
}

/**
 * 删除数组中的某个元素
 */
function removeArrItem(arr, dx) {
    if (isNaN(dx) || dx > arr.length) {
        return false;
    }
    for (i = 0, n = 0, void 0; i < arr.length; i++) {
        var i;
        var n;
        if (arr[i] != arr[dx]) {
            arr[n++] = arr[i];
        }
    }
    arr.length -= 1;
    return arr;
}
/**
 * 将字典转换为跳转路由的字符串
 * @param url 请求路径
 * {key1:value1,key2:value2} --> key1=value1&key2=value2
 */
function getStringWithDic(param) {
    var search = '';
    for (var key in param) {
        search += key + '=' + param[key] + '&';
    }
    search = search.substr(0, search.length - 1);
    return search;
}
// 防抖
var debouncetimer;
function setDebounce(fn, delay) {
    return () => {
        // if (debouncetimer) {
        clearTimeout(debouncetimer);
        // }
        debouncetimer = setTimeout(fn, delay);
    };
}
function parseQueryString(url) {
    var str = url.split('?')[1];
    var items = str.split('&');
    var arr;
    var name;
    var value;
    for (i = 0, l = items.length, void 0; i < l; i++) {
        var i;
        var l;
        arr = items[i].split('=');
        name = arr[0];
        value = arr[1];
        this[name] = value;
    }
}
/*
 * 判断当前val是否为空
 */
function isNull(val) {
    if (val == null || val == 'null' || val == '' || val == undefined || val == 'undefined') {
        return null;
    } else {
        return val;
    }
}
/*
 * 判断当前val是否为空
 */
function tirm(str) {
    if (isNull(str)) {
        return str.replace(/\s/g, '');
    } else {
        return str;
    }
}
/** 加载框 */
function loading() {
    
    uni.showLoading({
        title:''
    });
}
/** 隐藏加载框 */
function stopLoading() {
    
    uni.hideLoading();
}
//url传值方法
function getQueryString(href, name) {
    if (href.substr(0, 1) != '?') {
        href = '?' + href;
    }
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = href.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}
//比较两个日期差值
function DateDiff(sDate1, sDate2) {
    var aDate;
    var oDate1;
    var oDate2;
    var iDays;
    aDate = sDate1.split('-');
    oDate1 = new Date(aDate[0], aDate[1] - 1, aDate[2]);
    aDate = sDate2.split('-');
    oDate2 = new Date(aDate[0], aDate[1] - 1, aDate[2]);
    iDays = parseInt((oDate1 - oDate2) / 1000 / 60 / 60 / 24);
    return iDays;
}
//比较两个日期差值-带分钟和秒
function DateDiff2(sDate1, sDate2) {
    var oDate1 = new Date(sDate1);
    var oDate2 = new Date(sDate2);
    var allDay = parseInt((oDate2 - oDate1) / 1000 / 60 / 60 / 24);
    var hours = (oDate2 - oDate1) / 86400000;
    var difference = (hours - allDay) * 24;
    if (difference > 0) {
        if (difference > 23) {
            var iDays = allDay + 1 + '天';
        } else {
            var iDays = allDay + '天' + Math.round(difference) + '小时';
        }
    } else {
        var iDays = allDay + '天';
    }
    return iDays;
}
/**
 * 校验错误提示信息
 */
var errMes = {
    error_phone: '请输入正确的手机号！',
    null_phone: '请输入手机号! ',
    error_name: '请输入正确的姓名',
    error_eng_name: '英文姓名4~30个字母',
    error_cn_name: '中文姓名2~15个汉字',
    null_name: '请输入姓名！',
    error_email: '请输入正确的邮箱',
    null_email: '请输入邮箱 ',
    error_cardcode: '请输入正确的身份证号码',
    null_cardcode: '请输入身份证号码'
};
/**
 * 校验
 */
var check = {
    isPhone: function (str) {
        if (check.isNull(str)) {
            alertTip(errMes.null_phone);
            return false;
        }
        str = str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        var isPhoneReg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
        if (isPhoneReg.test(str)) {
            return true;
        } else {
            alertTip(errMes.error_phone);
            return false;
        }
    },
    isNull: function (str) {
        if (str == null || str == 'null' || str == '' || str == undefined || str == 'NaN' || str == '[]') {
            return true;
        } else {
            return false;
        }
    },
    isEmail: function (str) {
        if (check.isNull(str)) {
            alertTip(errMes.null_email);
            return false;
        }
        var isEmailReg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
        if (isEmailReg.test(str)) {
            return true;
        } else {
            alertTip(errMes.error_email);
            return false;
        }
    },
    isRealName: function (str) {
        if (check.isNull(str)) {
            alertTip(errMes.null_name);
            return false;
        }
        str = str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
        var regexp = /^[\u4e00-\u9fa5][\u4e00-\u9fa5·.]*[\u4e00-\u9fa5]$/g;
        if (regexp.test(str)) {
            if (str.length <= 20 && str.length >= 2) {
                return str.length <= 20 && str.length >= 2;
            } else {
                alertTip('中文姓名2~20个汉字');
                return false;
            }
        } else {
            alertTip(errMes.error_name);
            return false;
        }
    },
    isName: function (str) {
        if (check.isNull(str)) {
            alertTip(errMes.null_name);
            return false;
        }
        var regexp = /^[\u4e00-\u9fa5]{2,15}$/;
        var re = /^[a-zA-Z\/ ]{4,30}$/;
        var b1 = regexp.test(str);
        var b2 = re.test(str);
        if (!b1 && !b2) {
            alertTip(errMes.error_cn_name + '或' + errMes.error_eng_name);
            return false;
        }
        return true;
    },
    isCardCode: function (str) {
        if (check.isNull(str)) {
            alertTip(errMes.null_cardcode);
            return false;
        } else {
            var num = str.toUpperCase();
            if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num)) {
                alertTip(errMes.error_cardcode);
                return false;
            }
            var len;
            var re;
            len = num.length;
            if (len == 15) {
                re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
                var arrSplit = num.match(re);
                var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
                var bGoodDay;
                bGoodDay = dtmBirth.getYear() == Number(arrSplit[2]) && dtmBirth.getMonth() + 1 == Number(arrSplit[3]) && dtmBirth.getDate() == Number(arrSplit[4]);
                if (!bGoodDay) {
                    alertTip(errMes.error_cardcode);
                    return false;
                } else {
                    if (new Date().getYear() < dtmBirth.getYear()) {
                        return false;
                    } else {
                        var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                        var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                        var nTemp = 0;
                        var i;
                        num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
                        for (i = 0; i < 17; i++) {
                            nTemp += num.substr(i, 1) * arrInt[i];
                        }
                        num += arrCh[nTemp % 11];
                        return true;
                    }
                }
            }
            if (len == 18) {
                var code = str.split('');
                re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
                var arrSplit = num.match(re);
                var dtmBirth = new Date(arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
                var bGoodDay;
                bGoodDay = dtmBirth.getFullYear() == Number(arrSplit[2]) && dtmBirth.getMonth() + 1 == Number(arrSplit[3]) && dtmBirth.getDate() == Number(arrSplit[4]);
                if (!bGoodDay) {
                    alertTip(errMes.error_cardcode);
                    return false;
                } else {
                    var valnum;
                    var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                    var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                    var nTemp = 0;
                    var i;
                    for (i = 0; i < 17; i++) {
                        nTemp += num.substr(i, 1) * arrInt[i];
                    }
                    valnum = arrCh[nTemp % 11];
                    if (valnum.toLowerCase() != code[17].toLowerCase()) {
                        alertTip(errMes.error_cardcode);
                        return false;
                    }
                    return true;
                }
            }
            alertTip(errMes.error_cardcode);
            return false;
        }
    }
};
//出发地历史记录获取
var StartCityHistory = {
    id: '',
    findname: '',
    netaddress: '',
    netname: '',
    departtype: '',
    addHistory: function (p) {
        if (isNull(uni.getStorageSync('startHistory')) == null) {
            var arr = new Array();
            arr.push(p);
            uni.setStorageSync('startHistory', JSON.stringify(arr));
        } else {
            var isExist = false;
            var arr = JSON.parse(uni.getStorageSync('startHistory'));
            for (var i = 0; i < arr.length; i++) {
                // if (arr[i].id == p.id) {
                //   isExist = true;
                //   break;
                // }
                if (arr[i].id == p.id) {
                    isExist = true;
                    arr.splice(i, 1);
                }
            }
            if (!isExist) {
                if (arr.length < 5) {
                    arr.push(p);
                } else {
                    arr.reverse();
                    arr.pop();
                    arr.reverse();
                    arr.push(p);
                }
            } else {
                arr.push(p);
            }
            uni.setStorageSync('startHistory', JSON.stringify(arr));
        }
    },
    getHistory: function () {
        var arr = new Array();
        if (isNull(uni.getStorageSync('startHistory')) != null) {
            arr = JSON.parse(uni.getStorageSync('startHistory'));
        }
        arr.reverse();
        return arr;
    }
};
//星期转化
function getDays(y, m, d) {
    m = parseInt(m);
    m = m - 1;
    m = '0' + m;
    var date;
    if (y) {
        date = new Date(y, m, d);
    } else {
        date = new Date();
    }
    var weekDay = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    return weekDay[date.getDay()];
}
/**
 * YYMMDD转换为周几
 * @param {String} date
 */
function getWeeks(date) {
    if (!date || date.indexOf('-') == -1) {
        return;
    }
    let weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return weeks[new Date(date).getDay()];
}

/**
 * 计算与当前日期相差天数的日期
 */
function calculateDateWithDateAndcalculateCount(currentdate, daycount) {
    var dd = new Date(currentdate);
    dd.setDate(dd.getDate() + daycount); //获取daycount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份
    m = m < 10 ? '0' + m : m;
    var d = dd.getDate();
    d = d < 10 ? '0' + d : d;
    return y + '-' + m + '-' + d;
}
//日期不足两位补0
function addzero(datastr) {
    var datastrnow = datastr;
    if (datastrnow < 10) {
        datastrnow = '0' + datastrnow;
    }
    return datastrnow;
}
var CalendarData = new Array(100);
var madd = new Array(12);
var numString = '一二三四五六七八九十';
var monString = '正二三四五六七八九十冬腊';
var cYear;
var cMonth;
var cDay;
var TheDate;
CalendarData = new Array(
    2635,
    333387,
    1701,
    1748,
    267701,
    694,
    2391,
    133423,
    1175,
    396438,
    3402,
    3749,
    331177,
    1453,
    694,
    201326,
    2350,
    465197,
    3221,
    3402,
    400202,
    2901,
    1386,
    267611,
    605,
    2349,
    137515,
    2709,
    464533,
    1738,
    2901,
    330421,
    1242,
    2651,
    199255,
    1323,
    529706,
    3733,
    1706,
    398762,
    2741,
    1206,
    267438,
    2647,
    1318,
    204070,
    3477,
    461653,
    1386,
    2413,
    330077,
    1197,
    2637,
    268877,
    3365,
    531109,
    2900,
    2922,
    398042,
    2395,
    1179,
    267415,
    2635,
    661067,
    1701,
    1748,
    398772,
    2742,
    2391,
    330031,
    1175,
    1611,
    200010,
    3749,
    527717,
    1452,
    2742,
    332397,
    2350,
    3222,
    268949,
    3402,
    3493,
    133973,
    1386,
    464219,
    605,
    2349,
    334123,
    2709,
    2890,
    267946,
    2773,
    592565,
    1210,
    2651,
    395863,
    1323,
    2707,
    265877
);
madd[0] = 0;
madd[1] = 31;
madd[2] = 59;
madd[3] = 90;
madd[4] = 120;
madd[5] = 151;
madd[6] = 181;
madd[7] = 212;
madd[8] = 243;
madd[9] = 273;
madd[10] = 304;
madd[11] = 334;
//获取农历
function getLunarDay(solarYear, solarMonth, solarDay) {
    var that = this;
    if (solarYear < 1921 || solarYear > 2020) {
        return '';
    } else {
        solarMonth = parseInt(solarMonth) > 0 ? solarMonth - 1 : 11;
        e2c(solarYear, solarMonth, solarDay);
        return GetcDateString();
    }
    //return '六月十二'
}

function e2c() {
    var that = this;
    TheDate = arguments.length != 3 ? new Date() : new Date(arguments[0], arguments[1], arguments[2]);
    var total;
    var m;
    var n;
    var k;
    var isEnd = false;
    var tmp = TheDate.getYear();
    if (tmp < 1900) {
        tmp += 1900;
    }
    total = (tmp - 1921) * 365 + Math.floor((tmp - 1921) / 4) + madd[TheDate.getMonth()] + TheDate.getDate() - 38;
    if (TheDate.getYear() % 4 == 0 && TheDate.getMonth() > 1) {
        total++;
    }
    for (m = 0; ; m++) {
        k = CalendarData[m] < 4095 ? 11 : 12;
        for (n = k; n >= 0; n--) {
            if (total <= 29 + GetBit(CalendarData[m], n)) {
                isEnd = true;
                break;
            }
            total = total - 29 - GetBit(CalendarData[m], n);
        }
        if (isEnd) {
            break;
        }
    }
    cYear = 1921 + m;
    cMonth = k - n + 1;
    cDay = total;
    if (k == 12) {
        if (cMonth == Math.floor(CalendarData[m] / 65536) + 1) {
            cMonth = 1 - cMonth;
        }
        if (cMonth > Math.floor(CalendarData[m] / 65536) + 1) {
            cMonth--;
        }
    }
}
function GetcDateString() {
    var tmp = '';
    if (cMonth < 1) {
        tmp += monString.charAt(-cMonth - 1);
    } else {
        tmp += monString.charAt(cMonth - 1);
    }
    tmp += '月';
    tmp += cDay < 11 ? '初' : cDay < 20 ? '十' : cDay < 30 ? '二十' : '三十';
    if (cDay % 10 != 0 || cDay == 10) {
        tmp += numString.charAt((cDay - 1) % 10);
    }
    return tmp;
}
function GetBit(m, n) {
    return (m >> n) & 1;
}

//目的地历史记录获取
var DestinationCityHistory = {
    id: '',
    endcity: '',
    findname: '',
    netaddress: '',
    netname: '',
    enddeparttype: '',
    addHistory: function (p) {
        if (isNull(uni.getStorageSync('destintionHistory')) == null) {
            var arr = new Array();
            arr.push(p);
            uni.setStorageSync('destintionHistory', JSON.stringify(arr));
        } else {
            var isExist = false;
            var arr = JSON.parse(uni.getStorageSync('destintionHistory'));
            for (var i = 0; i < arr.length; i++) {
                // if (arr[i].findname == p.findname) {
                //   isExist = true;
                //   break;
                // }
                if (arr[i].findname == p.findname) {
                    isExist = true;
                    arr.splice(i, 1);
                }
            }
            if (!isExist) {
                if (arr.length < 5) {
                    arr.push(p);
                } else {
                    arr.reverse();
                    arr.pop();
                    arr.reverse();
                    arr.push(p);
                }
            } else {
                arr.push(p);
            }
            uni.setStorageSync('destintionHistory', JSON.stringify(arr));
        }
    },
    getHistory: function () {
        var arr = new Array();
        if (isNull(uni.getStorageSync('destintionHistory')) != null) {
            arr = JSON.parse(uni.getStorageSync('destintionHistory'));
        }
        arr.reverse();
        return arr;
    }
};
//线路历史记录获取
var lineCityHistory3 = {
    lineArr: uni.getStorageSync('lineCityHistory3') ? uni.getStorageSync('lineCityHistory3') : [],
    addlineHistory: function (lineCityHistoryObj) {
        this.lineArr = uni.getStorageSync('lineCityHistory3') ? uni.getStorageSync('lineCityHistory3') : [];
        var newArr = [];
        var isadd = true;
        var pos = -1;
        for (var i = 0; i < this.lineArr.length; i++) {
            if (this.lineArr[i].departid == lineCityHistoryObj.departid && this.lineArr[i].destination == lineCityHistoryObj.destination) {
                pos = i;
            }
        }
        if (pos >= 0) {
            this.lineArr.splice(pos, 1);
        }
        if (isadd == true) {
            newArr.push(lineCityHistoryObj);
            this.lineArr.forEach(function (o, i) {
                if (i < 4) {
                    newArr.push(o);
                }
            });
            this.lineArr = newArr;
        }
        uni.setStorageSync('lineCityHistory3', this.lineArr);
    },
    getlineHistory: function () {
        return this.lineAr[0];
    },
    clearlineHistory: function () {
        this.lineArr = [];
        uni.removeStorageSync('lineCityHistory3');
    }
};
/**
 * 获取拼接参数
 */
function getContactParamsString(paramMap) {
    var str = '';
    for (var key in paramMap) {
        str = str + key + '=' + paramMap[key] + '&';
    }
    var str = str.substring(0, str.length - 1);
    return str;
}
//乘车人
var MyRider = {
    id: '',
    name: '',
    idnum: '',
    phonenum: '',
    passengertype: '',
    freecount: 0,
    // 免费票数
    halfcount: 0,
    // 半价票数
    tickettype: '',
    // 票类型 2 半价 3 携童 5 优惠票 其他全价票
    addRider: function (p) {
        var myRider = uni.getStorageSync('myRider');
        if (check.isNull(myRider)) {
            var arr = new Array();
            arr.push(p);
            uni.setStorageSync('myRider', JSON.stringify(arr));
        } else {
            var arr = JSON.parse(myRider);
            var pos = -1;
            for (var i = 0; i < arr.length; i++) {
                //并且不为儿童
                if (arr[i].id == p.id && arr[i].passengertype != '2') {
                    pos = i;
                }
            }
            if (pos >= 0) {
                arr.splice(pos, 1, p);
            } else {
                arr.push(p);
            }
            uni.setStorageSync('myRider', JSON.stringify(arr));
        }
    },
    getRider: function (key) {
        var myRider = uni.getStorageSync('myRider');
        if (check.isNull(myRider)) {
            return null;
        }
        var rs = '';
        var pos = -1;
        var arr = JSON.parse(myRider);
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == key) {
                pos = i;
                break;
            }
        }
        if (pos >= 0) {
            rs = arr[pos];
        }
        return rs;
    },
    remove: function (p) {
        var myRider = uni.getStorageSync('myRider');
        if (check.isNull(myRider)) {
            return null;
        }
        var arr = JSON.parse(myRider);
        var pos = -1;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == p) {
                pos = i;
            }
        }
        if (pos >= 0) {
            arr.splice(pos, 1);
        }
        uni.setStorageSync('myRider', JSON.stringify(arr));
    },
    clear: function () {
        uni.removeStorageSync('myRider');
    },
    getRiderList: function () {
        var myRider = uni.getStorageSync('myRider');
        if (check.isNull(myRider)) {
            return null;
        }
        return JSON.parse(myRider);
    },
    riderToatalCount: function () {
        var riderInfos = [];
        var myRider = uni.getStorageSync('myRider');
        if (check.isNull(myRider)) {
            return 0;
        }
        riderInfos = JSON.parse(myRider);
        var totalcount = riderInfos.length;
        var o;
        for (var i in riderInfos) {
            o = riderInfos[i];
            if (o.halfcount) {
                totalcount = totalcount + o.halfcount;
            }
            if (o.freecount) {
                totalcount = totalcount + o.freecount;
            }
        }
        return totalcount;
    }
};
//专线乘车人
var SpecialineRider = {
    id: '',
    name: '',
    idnum: '',
    phonenum: '',
    passengertype: '',
    verificationflag: '',
    isclientadd: '1',
    birthday: '',
    sex: '',
    peopletype: '',
    email: '',
    engname: '',
    addRider: function (p) {
        var myRider = uni.getStorageSync('specialineRider');
        if (check.isNull(myRider)) {
            var arr = new Array();
            arr.push(p);
            uni.setStorageSync('specialineRider', JSON.stringify(arr));
        } else {
            var arr = JSON.parse(myRider);
            var pos = -1;
            for (var i = 0; i < arr.length; i++) {
                //并且不为儿童
                if (arr[i].id == p.id && arr[i].passengertype != '2') {
                    pos = i;
                }
            }
            if (pos >= 0) {
                arr.splice(pos, 1, p);
            } else {
                arr.push(p);
            }
            uni.setStorageSync('specialineRider', JSON.stringify(arr));
        }
    },
    getRider: function (key) {
        var myRider = uni.getStorageSync('specialineRider');
        if (check.isNull(myRider)) {
            return null;
        }
        var rs = '';
        var pos = -1;
        var arr = JSON.parse(myRider);
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == key) {
                pos = i;
                break;
            }
        }
        if (pos >= 0) {
            rs = arr[pos];
        }
        return rs;
    },
    remove: function (p) {
        var myRider = uni.getStorageSync('specialineRider');
        if (check.isNull(myRider)) {
            return null;
        }
        var arr = JSON.parse(myRider);
        var pos = -1;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == p) {
                pos = i;
            }
        }
        if (pos >= 0) {
            arr.splice(pos, 1);
        }
        uni.setStorageSync('specialineRider', JSON.stringify(arr));
    },
    allRider: function () {
        var arr = [];
        var myRider = uni.getStorageSync('specialineRider');
        if (check.isNull(myRider)) {
            return arr;
        }
        arr = JSON.parse(myRider);
        return arr;
    },
    getRiderCount: function () {
        var count = 0;
        var myRider = uni.getStorageSync('specialineRider');
        if (check.isNull(myRider)) {
            return count;
        }
        var arr = JSON.parse(myRider);
        return arr.length;
    },
    clear: function () {
        uni.removeStorageSync('specialineRider');
    }
};
//门票乘车人
var TripRider = {
    id: '',
    name: '',
    idnum: '',
    phonenum: '',
    passengertype: '',
    verificationflag: '',
    isclientadd: '1',
    birthday: '',
    sex: '',
    peopletype: '',
    email: '',
    engname: '',
    addRider: function (p) {
        var myRider = uni.getStorageSync('tripRider');
        if (check.isNull(myRider)) {
            var arr = new Array();
            arr.push(p);
            uni.setStorageSync('tripRider', arr);
        } else {
            var arr = myRider;
            var pos = -1;
            for (var i = 0; i < arr.length; i++) {
                //并且不为儿童
                if (arr[i].id == p.id && arr[i].passengertype != '2') {
                    pos = i;
                }
            }
            if (pos >= 0) {
                arr.splice(pos, 1, p);
            } else {
                arr.push(p);
            }
            uni.setStorageSync('tripRider', arr);
        }
    },
    getRider: function (key) {
        var myRider = uni.getStorageSync('tripRider');
        if (check.isNull(myRider)) {
            return null;
        }
        var rs = '';
        var pos = -1;
        var arr = myRider;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == key) {
                pos = i;
                break;
            }
        }
        if (pos >= 0) {
            rs = arr[pos];
        }
        return rs;
    },
    remove: function (p) {
        var myRider = uni.getStorageSync('tripRider');
        if (check.isNull(myRider)) {
            return null;
        }
        var arr = myRider;
        var pos = -1;
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].id == p) {
                pos = i;
            }
        }
        if (pos >= 0) {
            arr.splice(pos, 1);
        }
        uni.setStorageSync('tripRider', arr);
    },
    allRider: function () {
        var arr = [];
        var myRider = uni.getStorageSync('tripRider');
        if (check.isNull(myRider)) {
            return arr;
        }
        return myRider;
    },
    getRiderCount: function () {
        var count = 0;
        var myRider = uni.getStorageSync('tripRider');
        if (check.isNull(myRider)) {
            return count;
        }
        return myRider.length;
    },
    clear: function () {
        uni.removeStorageSync('tripRider');
    }
};
//计时
var timeFn;
var fn;
function countdow(staticTime, allTime, fu, lastFu) {
    if (timeFn) {
        clearInterval(timeFn);
        if (fn && typeof fn == 'function') {
            fn(0);
        }
        timeFn = null;
        fn = null;
    }
    // fn = lastFu;
    timeFn = setInterval(function () {
        var nowTime = new Date().getTime();
        var surplusTime = allTime - Math.floor((nowTime - staticTime) / 1000);
        if (surplusTime > 0) {
            fu(surplusTime);
        } else {
            clearInterval(timeFn);
            lastFu(0);
            timeFn = null;
            fn = null;
        }
    }, 1000);
    return function () {
        clearInterval(timeFn);
        timeFn = null;
        fn = null;
    };
}
function clearCountDow() {
    if (timeFn) {
        clearInterval(timeFn);
        timeFn = null;
        fn = null;
    }
}
// 创建节点并获取节点样式信息
function querySelectorInfo(selector, callback) {
    var arr = new Array();
    var query = uni.createSelectorQuery();
    query.select(selector).boundingClientRect();
    query.selectViewport().scrollOffset();
    query.exec(callback);
}
// 日期格式转换 例：dateFormat(new Date(), yyyy-MM-dd HH:mm:ss)
function dateFormat(date, fmt) {
    var o = {
        'M+': date.getMonth() + 1,
        //月份
        'd+': date.getDate(),
        //日
        'h+': date.getHours(),
        //小时
        'm+': date.getMinutes(),
        //分
        's+': date.getSeconds(),
        //秒
        'q+': Math.floor((date.getMonth() + 3) / 3),
        //季度
        S: date.getMilliseconds() //毫秒
    };

    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
        }
    }
    return fmt;
}
function getMinute(nowminiut, spacetime) {
    spacetime = parseInt(spacetime);
    var result = [];
    for (var i = nowminiut; i < 60; ) {
        var getresult = i;
        if (getresult < 10) {
            getresult = '0' + getresult;
        }
        result.push(getresult + '分');
        i = i + spacetime;
    }
    return result;
}
const formatTime = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();
    return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};
const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : '0' + n;
};

/**
 * 手机号加密 例如：159****4856
 */
const encryptionPhone = (phone) => {
    if (!phone || phone.length != 11) {
        phone = '';
    } else {
        phone = phone.substr(0, 3) + '****' + phone.substr(7);
    }
    return phone;
};

/**
 * 检测是否登录
 */
const checkIsLogin = (options) => {
    if (null == isNull(uni.getStorageSync('isAuthenLogin'))) {
        const redirectUrl = encodeURIComponent(options.url);
        uni.navigateTo({
            url: `/pages/user/authorize/authorize?url=${redirectUrl}&typehref=${options.typehref}`
        });
    } else {
        return true;
    }
};
/**
 * 检测活动有效性
 */
const checkActiveEffect = function (params) {
    return new Promise(function (resolve, reject) {
        let that = this;
        let header = null;
        let success = function (res) {
            if (!res.success) {
                return;
            }
            resolve(res);
        };
        let fail = function (err) {
            reject(err);
        };
        requestLoading(
            params.url,
            {
                position: params.position
            },
            reqestMethod.GET,
            header,
            null,
            null,
            success,
            fail,
            true
        );
    });
};
/**
 * 检测活动有效性
 * @parames {Object} params {activeid:""}
 *
 */
const getQueryActive = function (params) {
    return new Promise(function (resolve, reject) {
        let that = this;
        let header = null;
        let success = function (res) {
            if (res.status == '0000') {
                resolve(res);
            } else {
                resolve(null);
            }
        };
        let fail = function (err) {
            reject(err);
        };
        requestLoading(
            params.url,
            {
                activeid: params.activeid,
                buscode: params.buscode
            },
            reqestMethod.GET,
            header,
            null,
            null,
            success,
            fail
        );
    });
};
/**
 * 删除地址栏参数中的某个参数
 * @param {string}
 * @returns search
 */
const delParama = function (search, key) {
    if (isNull(url) == null) {
        var url = '';
    }
    if (search.indexOf(key) != -1) {
        var search_arr = search.split('&');
        var url_arr = [];
        for (var i = 0; i < search_arr.length; i++) {
            var temp = search_arr[i].split('=');
            if (key != temp[0]) {
                url_arr.push(search_arr[i]);
            }
        }
        url = url_arr.join('&');
    } else {
        url = search;
    }
    return url;
};
/**
 * 获取小程序token
 */
function getweixxToken() {
    var token = {};
    //暂时使用web调试
    // token.clienttype = 'android';
    token.clienttype = uni.getStorageSync('fromto');
    // token.clienttype = 'weix';
    //uni.setStorageSync('clienttoken', '5F323D104358E614518AD233FF3305FEEED6F6A41A54319EDB7677A1A0D7FE7A23103082F16EDFB0E793DBC33CA27681681995F07D11555266BEC26CC5B1A812693835CDDBF775B51E6416111E05C4527BCCD97C4602B961F1AEF9B2519CBFB36113981ADB5C539EF35B9FB12D22582C574A84AD281356619B84DE009CF9F6C9');
    //uni.setStorageSync('isAuthenLogin', 1);
    token.clienttoken = uni.getStorageSync('clienttoken') || '';
    token.ordertoken = uni.getStorageSync('ordertoken') || '';
    // token.devicetoken = wx.getStorageSync('clienttoken') || '';
    token.version = VERSION;
    return token;
}
/**
 * 数组去重
 */
function arrayUnique(arr, u_key) {
    let map = new Map();
    arr.forEach((item, index) => {
        if (!map.has(item[u_key])) {
            map.set(item[u_key], item);
        }
    });
    return [...map.values()];
}
const getLocation = function (type, success, fail) {
    if (type == null || type == '') {
        type = 'wgs84';
    }
    uni.getSetting({
        'scope.userLocation': true,
        'scope.userInfo': true,
        success: function (data) {
            uni.getLocation({
                type: type,
                success: function (res) {
                    success(res);
                },
                fail: function (data) {
                    fail(data);
                }
            });
        },
        fail: function (data) {
            fail(data);
        }
    });
};

/*
 * 埋点-api上报
 * obj.type,类型：weix-微信api上报；baidu-百度api上报
 * obj.name, 事件名称 （注：需要在微信公众平台/百度统计配置））
 * obj.reportobj, 需要上报的自定义参数合集（注：需要在微信公众平台/百度统计配置）
 */
function apiReport(obj) {
    var type = obj.type;
    switch (type) {
        case 'weix':
            //微信上报
            console.log('微信上报', obj);
            uni.reportAnalytics(obj.name, obj.reportobj);
            break;
        case 'baidu':
            //百度上报
            console.log('百度上报', obj);
            getApp().globalData.mtj.trackEvent(obj.name, obj.reportobj);
            break;
    }
}
/**
 * 基础的base64解码工具
 */
function getBase64() {
    var Base64 = {
        _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
        encode: function (e) {
            var t = '';
            var n;
            var r;
            var i;
            var s;
            var o;
            var u;
            var a;
            var f = 0;
            e = Base64._utf8_encode(e);
            while (f < e.length) {
                n = e.charCodeAt(f++);
                r = e.charCodeAt(f++);
                i = e.charCodeAt(f++);
                s = n >> 2;
                o = ((n & 3) << 4) | (r >> 4);
                u = ((r & 15) << 2) | (i >> 6);
                a = i & 63;
                if (isNaN(r)) {
                    u = a = 64;
                } else if (isNaN(i)) {
                    a = 64;
                }
                t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a);
            }
            return t;
        },
        decode: function (e) {
            var t = '';
            var n;
            var r;
            var i;
            var s;
            var o;
            var u;
            var a;
            var f = 0;
            e = e.replace(/[^A-Za-z0-9+/=]/g, '');
            while (f < e.length) {
                s = this._keyStr.indexOf(e.charAt(f++));
                o = this._keyStr.indexOf(e.charAt(f++));
                u = this._keyStr.indexOf(e.charAt(f++));
                a = this._keyStr.indexOf(e.charAt(f++));
                n = (s << 2) | (o >> 4);
                r = ((o & 15) << 4) | (u >> 2);
                i = ((u & 3) << 6) | a;
                t = t + String.fromCharCode(n);
                if (u != 64) {
                    t = t + String.fromCharCode(r);
                }
                if (a != 64) {
                    t = t + String.fromCharCode(i);
                }
            }
            t = Base64._utf8_decode(t);
            return t;
        },
        _utf8_encode: function (e) {
            e = e.replace(/rn/g, 'n');
            var t = '';
            for (var n = 0; n < e.length; n++) {
                var r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r);
                } else if (r > 127 && r < 2048) {
                    t += String.fromCharCode((r >> 6) | 192);
                    t += String.fromCharCode((r & 63) | 128);
                } else {
                    t += String.fromCharCode((r >> 12) | 224);
                    t += String.fromCharCode(((r >> 6) & 63) | 128);
                    t += String.fromCharCode((r & 63) | 128);
                }
            }
            return t;
        },
        _utf8_decode: function (e) {
            var t = '';
            var n = 0;
            var r = 0;
            var c2 = 0;
            while (n < e.length) {
                r = e.charCodeAt(n);
                if (r < 128) {
                    t += String.fromCharCode(r);
                    n++;
                } else if (r > 191 && r < 224) {
                    c2 = e.charCodeAt(n + 1);
                    t += String.fromCharCode(((r & 31) << 6) | (c2 & 63));
                    n += 2;
                } else {
                    c2 = e.charCodeAt(n + 1);
                    c3 = e.charCodeAt(n + 2);
                    t += String.fromCharCode(((r & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    n += 3;
                }
            }
            return t;
        }
    };
    return Base64;
}
var debounce = (function () {
    let timer = null;
    return function (fn, delay) {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(fn, delay);
    };
})();
export default{
    VERSION,
    formatTime,
    dateFormat,
    reqestMethod,
    requestLoading,
    getStringWithDic,
    check,
    getContactParamsString,
    StartCityHistory,
    DestinationCityHistory,
    lineCityHistory3,
    getDays,
    loading,
    stopLoading,
    isNull,
    tirm,
    MyRider,
    getQueryString,
    parseQueryString,
    DateDiff,
    DateDiff2,
    addzero,
    getLunarDay,
    querySelectorInfo,
    countdow: countdow,
    clearCountDow,
    encryptionPhone,
    checkIsLogin,
    checkActiveEffect,
    delParama,
    getQueryActive,
    removeArrItem,
    getweixxToken,
    calculateDateWithDateAndcalculateCount,
    SpecialineRider,
    getWeeks,
    TripRider,
    getShowWeek,
    addzero,
    getLunarDay,
    arrayUnique,
    compareTime,
    getWeek,
    getHours,
    getMinute,
    getLocation,
    apiReport,
    debounce,
    requestAfterLogin,
    getBase64,
    isWeiXin,
	getToday,
	setDebounce
};
